<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{#if isNew}}新建{{else}}编辑{{/if}}解决方案</title>
    <script src="/apps/js/baidu-tongji-mtx.js"></script>
    <link rel="stylesheet" href="/apps/css/bootstrap.min.css">
    <link href="/apps/css/fontawesome-free-6.4.0-web/css/all.css" rel="stylesheet">
    <style>
        .form-text {
            font-size: 0.8rem;
        }
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        .ref-item {
            background-color: #f8f9fa;
            padding: 1rem;
            border-radius: 0.25rem;
        }
    </style>
</head>
<body>
<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">{{#if isNew}}新建{{else}}编辑{{/if}}解决方案</h5>
                </div>
                <div class="card-body">
                    <form action="/apps/admin/products/save" method="POST" id="productForm">
                        <input type="hidden" name="id" value="{{product.id}}">

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="name" class="form-label">名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="name" name="name" value="{{product.name}}" required>
                            </div>
                            <div class="col-md-6">
                                <label for="title" class="form-label">标题 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="title" name="title" value="{{product.title}}" required>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label for="category" class="form-label">分类 <span class="text-danger">*</span></label>
                                <select class="form-select" id="category" name="category" required>
                                    <option value="">选择分类</option>
                                    <option value="微生态制剂" {{#if (eq product.category "微生态制剂")}}selected{{/if}}>微生态制剂</option>
                                    <option value="膳食模式" {{#if (eq product.category "膳食模式")}}selected{{/if}}>膳食模式</option>
                                    <option value="营养补充剂" {{#if (eq product.category "营养补充剂")}}selected{{/if}}>营养补充剂</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="evidence_level" class="form-label">证据等级 <span class="text-danger">*</span></label>
                                <select class="form-select" id="evidence_level" name="evidence_level" required>
                                    <option value="">选择证据等级</option>
                                    <option value="高质量证据" {{#if (eq product.evidence_level "高质量证据")}}selected{{/if}}>高质量证据</option>
                                    <option value="强质量证据" {{#if (eq product.evidence_level "强质量证据")}}selected{{/if}}>强质量证据</option>
                                    <option value="回顾性证据" {{#if (eq product.evidence_level "回顾性证据")}}selected{{/if}}>回顾性证据</option>
                                    <option value="启发性证据" {{#if (eq product.evidence_level "启发性证据")}}selected{{/if}}>启发性证据</option>
                                    <option value="其它证据" {{#if (eq product.evidence_level "其它证据")}}selected{{/if}}>其它证据</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="sort_order" class="form-label">排序</label>
                                <input type="number" class="form-control" id="sort_order" name="sort_order" value="{{product.sort_order}}" min="1">
                                <small class="form-text text-muted">数字越小排序越靠前</small>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label for="tagsInput" class="form-label">标签 <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="tagsInput" name="tags" placeholder="多个标签用英文逗号分隔" value="{{#each product.tags}}{{this}}{{#unless @last}},{{/unless}}{{/each}}">
                                    <button type="button" class="btn btn-outline-primary" id="openTagSelector">选择标签</button>
                                </div>
                                <div class="form-text">可手工输入，也可点击右侧按钮批量选择</div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label for="spec" class="form-label">规格/特点</label>
                                <input type="text" class="form-control" id="spec" name="spec" value="{{product.spec}}">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label for="image" class="form-label">图片URL</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="image" name="image" value="{{product.image}}">
                                    <button class="btn btn-outline-secondary" type="button" id="uploadImageBtn">上传</button>
                                </div>
                                <div class="mt-2" id="imagePreview">
                                    {{#if product.image}}
                                    <img src="{{product.image}}" alt="图片预览" style="max-width: 200px; max-height: 200px;">
                                    {{/if}}
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label for="summary" class="form-label">摘要 <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="summary" name="summary" rows="4" required>{{product.summary}}</textarea>
                                <small class="form-text text-muted">支持HTML标签，如&lt;br&gt;换行</small>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="detail" class="form-label">详情页URL</label>
                                <input type="text" class="form-control" id="detail" name="detail" value="{{product.detail}}">
                            </div>
                            <div class="col-md-6">
                                <label for="path" class="form-label">小程序路径</label>
                                <input type="text" class="form-control" id="path" name="path" value="{{product.path}}">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-3">
                                <label for="view_count" class="form-label">浏览量</label>
                                <input type="number" class="form-control" id="view_count" name="view_count" value="{{product.view_count}}" min="0">
                            </div>
                            <div class="col-md-3">
                                <label for="like_count" class="form-label">点赞数</label>
                                <input type="number" class="form-control" id="like_count" name="like_count" value="{{product.like_count}}" min="0">
                            </div>
                            <div class="col-md-3">
                                <label for="bookmark_count" class="form-label">收藏数</label>
                                <input type="number" class="form-control" id="bookmark_count" name="bookmark_count" value="{{product.bookmark_count}}" min="0">
                            </div>
                            <div class="col-md-3">
                                <label for="comment_count" class="form-label">评论数</label>
                                <input type="number" class="form-control" id="comment_count" name="comment_count" value="{{product.comment_count}}" min="0">
                            </div>
                        </div>

                        <div class="row mb-4">
                            <div class="col-md-12">
                                <label for="refs" class="form-label">参考文献</label>
                                <div class="card">
                                    <div class="card-body">
                                        <div id="refsContainer">
                                            {{#each product.refs}}
                                            <div class="ref-item mb-3">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">文献标题</label>
                                                        <input type="text" class="form-control ref-title" value="{{this.title}}">
                                                    </div>
                                                    <div class="col-md-5">
                                                        <label class="form-label">详情链接</label>
                                                        <input type="text" class="form-control ref-detail" value="{{this.detail}}">
                                                    </div>
                                                    <div class="col-md-1 d-flex align-items-end">
                                                        <button type="button" class="btn btn-outline-danger remove-ref-btn">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                            {{/each}}
                                        </div>
                                        <input type="hidden" id="refs" name="refs" value="{{json product.refs}}">
                                        <button type="button" class="btn btn-outline-primary btn-sm" id="addRefBtn">
                                            <i class="fas fa-plus"></i> 添加参考文献
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12 d-flex justify-content-between">
                                <a href="/apps/admin/products" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left"></i> 返回列表
                                </a>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> 保存
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js" defer></script>
<script src="/apps/js/bootstrap.bundle.min.js" defer></script>
<script src="/apps/js/wx-client-dom.js" defer></script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 图片预览
        const imageInput = document.getElementById('image');
        const imagePreview = document.getElementById('imagePreview');

        imageInput.addEventListener('change', function() {
            const imageUrl = this.value.trim();
            if (imageUrl) {
                imagePreview.innerHTML = `<img src="${imageUrl}" alt="图片预览" style="max-width: 200px; max-height: 200px;">`;
            } else {
                imagePreview.innerHTML = '';
            }
        });

        // 处理参考文献
        const refsContainer = document.getElementById('refsContainer');
        const refsInput = document.getElementById('refs');
        const addRefBtn = document.getElementById('addRefBtn');

        // 添加参考文献
        addRefBtn.addEventListener('click', function() {
            const refItem = document.createElement('div');
            refItem.className = 'ref-item mb-3';
            refItem.innerHTML = `
                <div class="row">
                    <div class="col-md-6">
                        <label class="form-label">文献标题</label>
                        <input type="text" class="form-control ref-title" value="">
                    </div>
                    <div class="col-md-5">
                        <label class="form-label">详情链接</label>
                        <input type="text" class="form-control ref-detail" value="">
                    </div>
                    <div class="col-md-1 d-flex align-items-end">
                        <button type="button" class="btn btn-outline-danger remove-ref-btn">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            `;
            refsContainer.appendChild(refItem);

            // 绑定删除按钮事件
            refItem.querySelector('.remove-ref-btn').addEventListener('click', function() {
                refItem.remove();
                updateRefsInput();
            });

            // 绑定输入框变更事件
            const inputs = refItem.querySelectorAll('input');
            inputs.forEach(input => {
                input.addEventListener('change', updateRefsInput);
            });
        });

        // 绑定现有参考文献的删除按钮
        document.querySelectorAll('.remove-ref-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                this.closest('.ref-item').remove();
                updateRefsInput();
            });
        });

        // 绑定现有参考文献的输入框变更事件
        document.querySelectorAll('.ref-title, .ref-detail').forEach(input => {
            input.addEventListener('change', updateRefsInput);
        });

        // 更新参考文献隐藏输入框
        function updateRefsInput() {
            const refs = [];
            document.querySelectorAll('.ref-item').forEach((item, index) => {
                const title = item.querySelector('.ref-title').value.trim();
                const detail = item.querySelector('.ref-detail').value.trim();

                if (title || detail) {
                    refs.push({
                        id: index + 1,
                        title: title,
                        detail: detail,
                        path: ''
                    });
                }
            });

            refsInput.value = JSON.stringify(refs);
        }

        // 文件上传
        document.getElementById('uploadImageBtn').addEventListener('click', async function() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*';

            input.onchange = async function() {
                if (!this.files.length) return;

                const file = this.files[0];
                const formData = new FormData();
                formData.append('file', file);
                formData.append('uid', '{{req.session.totemUID}}');
                formData.append('code', 'mta-product');

                try {
                    const response = await fetch('https://mall.totembio.cn/api/uploadMtaFile', {
                        method: 'POST',
                        body: formData
                    });

                    const result = await response.json();

                    if (result.status == 200 && result.data && result.data.src) {
                        document.getElementById('image').value = result.data.src;
                        document.getElementById('imagePreview').innerHTML = `
                            <img src="${result.data.src}" alt="图片预览" style="max-width: 200px; max-height: 200px;">
                        `;
                    } else {
                        alert('上传失败: ' + (result.message || '未知错误'));
                    }
                } catch (error) {
                    alert('上传失败: ' + error.message);
                }
            };

            input.click();
        });

        // 表单提交前更新参考文献
        document.getElementById('productForm').addEventListener('submit', function(e) {
            updateRefsInput();
        });

        // 初始更新一次参考文献
        updateRefsInput();

        // 标签树状弹窗选择功能
        document.getElementById('openTagSelector').addEventListener('click', async function() {
            const tagTree = document.getElementById('tagTree');
            // 只加载一次树
            if (!tagTree.hasChildNodes()) {
                const res = await fetch('/apps/data/diseases/categories');
                const result = await res.json();
                if (result.code !== 0) return;
                const categories = result.data;
                const treeHtml = categories.map(cat => `
                    <div>
                        <strong>${cat.name}</strong>
                        <div style="margin-left:1.5em;">
                            ${cat.sub_categories.map(sub => `
                                <div class=\"form-check form-check-inline\">
                                    <input class=\"form-check-input tag-tree-checkbox\" type=\"checkbox\" value=\"${sub}\" id=\"tag-${cat.name}-${sub}\">
                                    <label class=\"form-check-label\" for=\"tag-${cat.name}-${sub}\">${sub}</label>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `).join('');
                tagTree.innerHTML = treeHtml;
            }
            // 回填已选
            const currentTags = document.getElementById('tagsInput').value.split(',').map(t => t.trim()).filter(Boolean);
            document.querySelectorAll('.tag-tree-checkbox').forEach(cb => {
                cb.checked = currentTags.includes(cb.value);
            });
            var modal = new bootstrap.Modal(document.getElementById('tagSelectorModal'));
            modal.show();
        });
        // 确认选择
        document.getElementById('confirmTagSelection').addEventListener('click', function() {
            const checked = Array.from(document.querySelectorAll('.tag-tree-checkbox:checked')).map(cb => cb.value);
            const input = document.getElementById('tagsInput');
            const manual = input.value.split(',').map(t => t.trim()).filter(Boolean);
            const all = Array.from(new Set([...manual, ...checked]));
            input.value = all.join(',');
            bootstrap.Modal.getInstance(document.getElementById('tagSelectorModal')).hide();
        });
    });
</script>

<!-- 标签选择弹窗 -->
<div class="modal fade" id="tagSelectorModal" tabindex="-1" aria-labelledby="tagSelectorModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="tagSelectorModalLabel">选择标签</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
      </div>
      <div class="modal-body">
        <div id="tagTree"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="confirmTagSelection">确认选择</button>
      </div>
    </div>
  </div>
</div>
</body>
</html>
